<template>
  <div class="form-container">
    <h3>{{ form.id ? '编辑测试用例' : '创建测试用例' }}</h3>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>用例名称 *</label>
        <input v-model="form.name" placeholder="请输入用例名称" required />
      </div>

      <div class="form-group">
        <label>请求地址 *</label>
        <input v-model="form.url" placeholder="https://api.example.com/users" required />
      </div>

      <div class="form-row">
        <div class="form-group">
          <label>请求方法</label>
          <select v-model="form.method">
            <option value="GET">GET</option>
            <option value="POST">POST</option>
            <option value="PUT">PUT</option>
            <option value="DELETE">DELETE</option>
          </select>
        </div>

        <div class="form-group">
          <label>期望状态码 *</label>
          <input v-model.number="form.expected_status" type="number" required />
        </div>
      </div>

      <div class="form-group">
        <label>请求头 (JSON)</label>
        <textarea
          v-model="headersStr"
          placeholder='{ "Content-Type": "application/json", "Authorization": "Bearer xxx" }'
          rows="3"
        ></textarea>
      </div>

      <div class="form-group">
        <label>请求体 (JSON)</label>
        <textarea
          v-model="bodyStr"
          placeholder='{ "name": "张三", "email": "zhang@example.com" }'
          rows="4"
          :disabled="form.method === 'GET' || form.method === 'DELETE'"
        ></textarea>
      </div>

      <div class="form-group">
        <label>期望响应 (JSON)</label>
        <textarea
          v-model="expectedResponseStr"
          placeholder='{ "success": true }'
          rows="3"
        ></textarea>
      </div>

      <div class="form-actions">
        <button type="submit" class="btn-primary" @click="handleClick">
          {{ form.id ? '更新' : '创建' }}
        </button>
        <button type="button" @click="resetForm" class="btn-secondary">重置</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, defineEmits, computed, watch, onMounted, defineProps } from 'vue'
import api from '../services/api'

const emit = defineEmits(['refresh', 'handle_create', 'handle_update'])
const props = defineProps({
  editingCase: {
    type: Object,
    default: () => ({}),
  },
})
// 表单数据
const form = ref({
  name: '',
  url: '',
  method: 'GET',
  headers: '',
  body: '',
  expected_status: 200,
  expected_response: '',
})

// 重置表单
const resetForm = () => {
  console.log('重置了')
  form.value = {
    name: '',
    url: '',
    method: 'GET',
    headers: '{}',
    body: '{}',
    expected_status: 200,
    expected_response: '{}',
  }
}

// 保存用例
// const saveCase = async () => {
//   try {
//     // ✅ 提交前：把 JSON 字符串解析成对象
//     const payload = {
//       name: form.value.name,
//       url: form.value.url,
//       method: form.value.method,
//       expected_status: form.value.expected_status,

//       // 🎯 关键：JSON.parse 并处理异常
//       headers: safeParse(form.value.headers, '{}', '请求头'),
//       body: safeParse(form.value.body, 'null', '请求体'),
//       expected_response: safeParse(form.value.expected_response, '{}', '期望响应'),
//     }

//     // ✅ 发送对象，axios 会自动 JSON.stringify
//     const res = await api.post('/test-cases/', payload)
//     alert('创建成功！')
//   } catch (error) {
//     console.error(error)
//   }
//   // 可选：重置表单
//   resetForm()
// }

const headersStr = computed({
  get() {
    // 对象 → 字符串（用于显示）
    return form.value.headers
      ? JSON.stringify(form.value.headers, null, 2)
      : '{\n  "Content-Type": "application/json"\n}'
  },
  set(val) {
    // 字符串 → 对象（用于内部存储）
    try {
      form.value.headers = val ? JSON.parse(val) : {}
    } catch (e) {
      console.warn('Headers 解析失败', e)
      // 可选：保留用户输入
    }
  },
})

const bodyStr = computed({
  get() {
    return form.value.body ? JSON.stringify(form.value.body, null, 2) : '{\n\n}'
  },
  set(val) {
    try {
      form.value.body = val ? JSON.parse(val) : null
    } catch (e) {
      console.warn('Body 解析失败', e)
    }
  },
})

const expectedResponseStr = computed({
  get() {
    return form.value.expected_response
      ? JSON.stringify(form.value.expected_response, null, 2)
      : '{\n\n}'
  },
  set(val) {
    try {
      form.value.expected_response = val ? JSON.parse(val) : {}
    } catch (e) {
      console.warn('Expected Response 解析失败', e)
    }
  },
})

const handleSubmit = () => {
  if (form.value.id) {
    //更新
    emit('handle_update', form.value)
  } else {
    //创建
    emit('handle_create', form.value)
  }
  // 可选：重置表单
  resetForm()
}

defineExpose({
  resetForm,
})

watch(
  () => props.editingCase,
  (newVal) => {
    if (newVal && typeof newVal === 'object') {
      console.log('编辑用例更新:', newVal)

      // ✅ 直接赋值对象，computed 会自动转为字符串显示
      form.value = {
        ...newVal,
        // headers/body 是对象，但 computed 会转为字符串
      }
    }
  },
  { immediate: true },
)
</script>

<style scoped>
.form-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 30px;
}

.form-container h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.form-row {
  display: flex;
  gap: 15px;
}

.form-group {
  flex: 1;
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

input,
select,
textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

input:focus,
select:focus,
textarea:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

textarea:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.btn-primary {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary:hover {
  background-color: #3aa876;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-secondary:hover {
  background-color: #5a6268;
}
</style>
